import docxtemplater from 'docxtemplater'
import Pizzip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { saveAS } from 'file-saver'

/**
 * 导出docx
 * @param{ String } tempDocxPath 模板文件路径
 * @param{ Object } data 文件中传入的数据
 * @param{ String } fileName 导出的文件名
 */
export const exportDocx = (tempDocxPath, data, fileName) => {
  JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
    if (error) {
      throw  error
    }
    let zip = new Pizzip(content)
    let doc = new docxtemplater().loadZip(zip)
    doc.setData(data)
    try {
      doc.render()
    } catch (error) {
      let e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      }
      console.log({ error: e })
      throw error
    }
    let out = doc.getZip().generate({
      type: 'blod',
      mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    })

    saveAS(out, fileName)

  })
}